﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Input;
using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.Context;
using Rio.Framework.Pages.Manager;
using Rio.Framework.WCFService;
using Rio.Framework.WCFService.RioWcfServices;
using Telerik.Windows;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.DragDrop;
using Document = NetBay.Core.BusinessEntities.Document;
using Folder = NetBay.Core.BusinessEntities.Folder;
using Rio.Framework.Pages.AppCode.Enums;
using NetBay.Core.Silverlight.Log;
using System.Net;

namespace Rio.Framework.Pages.Viewer
{
    public partial class ListVignetteSearch
    {
        #region Attributes

        private ObservableCollection<ImageRioSearch> m_ListItemSource;
        private readonly bool m_bCanModify = true;

        #endregion

        #region Properties

        public override bool ScanImportIsEnabled
        {
            get
            {
                return base.ScanImportIsEnabled;
            }
            set
            {
                base.ScanImportIsEnabled = value;
                if (DocumentToolbar != null)
                {
                    DocumentToolbar.ScanImportIsEnabled = value;
                    DocumentToolbar.ManageToolbar();
                }
            }
        }

        /// <summary>
        /// Gets or sets the list item source.
        /// </summary>
        /// <value>The list item source.</value>
        public ObservableCollection<ImageRioSearch> ListItemSource
        {
            get
            {
                return m_ListItemSource;
            }
            set
            {
                m_ListItemSource = value;
                OnPropertyChanged("ListItemSource");
            }
        }

        /// <summary>
        /// Gets the list box items.
        /// </summary>
        /// <value>The list box items.</value>
        public ItemCollection ListBoxItems
        {
            get
            {
                return ListBoxVignette.Items;
            }
        }

        /// <summary>
        /// Activate thumbnails user control
        /// </summary>
        /// <param name="p_iSelectedDocumentIndex">Index of the p_i selected document.</param>
        public void Activate(int p_iSelectedDocumentIndex)
        {
            if (ListBoxVignette.Items.Count > 0 || p_iSelectedDocumentIndex == -1)
            {
                if (p_iSelectedDocumentIndex < ListBoxVignette.Items.Count)
                {
                    ListBoxVignette.SelectedIndex = p_iSelectedDocumentIndex;
                }
                else
                {
                    ListBoxVignette.SelectedIndex = -1;
                }
            }
            Visibility = Visibility.Visible;
        }

        /// <summary>
        /// Desactivate thumbnail user control
        /// </summary>
        public void Desactivate()
        {
            if (ListBoxVignette.SelectedItems != null && ListBoxVignette.SelectedItems.Count > 0)
            {
                ImageRioSearch l_oSelectedItem = (ImageRioSearch)ListBoxVignette.SelectedItems[0];
                ClearSelectedThumbnails();
                ListBoxVignette.SelectedItems.Add(l_oSelectedItem);
            }
            Visibility = Visibility.Collapsed;
        }
        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ListVignetteSearch" /> class.
        /// </summary>
        public ListVignetteSearch()
            : base(null, AppDisplayMode.Search)
        {
            InitClass();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ListVignetteSearch" /> class.
        /// </summary>
        /// <param name="p_oListDocument">The p_o list document.</param>
        /// <param name="p_oCurrentFolder">The p_o current folder.</param>
        /// <param name="p_bCanModify">The P_B can modify.</param>
        /// <param name="p_oOrganization">The p_o organization.</param>
        /// <param name="p_oFolderType">Type of the p_o folder.</param>
        public ListVignetteSearch(List<Document> p_oListDocument, Folder p_oCurrentFolder, bool p_bCanModify = true, NetBay.Core.BusinessEntities.Organization p_oOrganization = null, NetBay.Core.BusinessEntities.FolderType p_oFolderType = null)
            : base(p_oListDocument, AppDisplayMode.Search)
        {
            m_bCanModify = p_bCanModify;
            m_oFolder = p_oCurrentFolder;
            m_oCurrentFolderType = p_oFolderType;
            m_oCurrentOrganization = p_oOrganization;
            InitClass();
        }

        /// <summary>
        /// Inits the class.
        /// </summary>
        private void InitClass()
        {
            InitializeComponent();

            //Initialize document toolbar
            DocumentToolbar.AppDisplayMode = AppDisplayMode.Search;
            DocumentContextMenu.AppDisplayMode = AppDisplayMode.Search;
            ActivateKeyPress();

            InitLabel();

            //Init Document toolbar
            DocumentToolbar.DocumentRibbonBarEvent += DocumentToolbar_DocumentRibbonBarEvent;
            DocumentToolbar.ViewMode = AppViewMode.Thumbnail;
            DocumentToolbar.ManageToolbar();

            //Init document context menu
            RadContextMenu.SetContextMenu(ListBoxVignette, DocumentContextMenu.ContextMenu);
            DocumentContextMenu.ViewMode = AppViewMode.Thumbnail;
            DocumentContextMenu.ManageContextMenuItemState();
            DocumentContextMenu.DocumentContextMenuEvent += DocumentToolbar_DocumentRibbonBarEvent;

            //Events for drag and drop
            ListBoxVignette.AddHandler(RadDragAndDropManager.DropQueryEvent, new EventHandler<DragDropQueryEventArgs>(OnDropQuery));
            ListBoxVignette.AddHandler(RadDragAndDropManager.DragQueryEvent, new EventHandler<DragDropQueryEventArgs>(OnDragQuery));
            ListBoxVignette.AddHandler(RadDragAndDropManager.DropInfoEvent, new EventHandler<DragDropEventArgs>(OnDropInfo));
        }

        #endregion

        #region Initialization

        /// <summary>
        /// Translation
        /// </summary>
        public override void InitLabel()
        {
            base.InitLabel();

            try
            {
                // Set tooltip
                ThumbResize.SetValue(ToolTipService.ToolTipProperty, Resx.GetLabel(ResxListVignetteSearch.RESIZETHUMBNAIL));

                //Labels & Textblock
                LabelSaveModificationImage = Resx.GetLabel(ResxListVignetteSearch.SAVE_MODIFICATION_CONFIRMATION);
                LabelDeleteThumbnail = Resx.GetLabel(ResxListVignetteSearch.DELETE_THUMBNAIL_CONFIRMATION);
                LabelRotateUnsupportedFile = Resx.GetLabel(ResxListVignetteSearch.ROTATE_UNSUPPORTED_FILE);
                TextBlockMode.Text = Resx.GetLabel(ResxCommon.MODE_THUMBNAIL);
            }
            catch (Exception ex)
            {
                Logger.Write("EXCEPTION : " + Environment.NewLine + ex, Logger.Level.Error);
            }
        }

        #endregion

        #region Selected vignette item event to display

        /// <summary>
        /// Click on listbox's item
        /// If it's a double click, we raise an event: "itemSelected"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Item_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                OnItemsSelectedToDisplay(GetListDocumentFromSelectedThumbnails());
            }
        }

        #endregion

        #region Events
        /// <summary>
        /// Protected method for raise the event 'ListDocumentUpdated'
        /// </summary>
        protected override void OnListDocumentUpdated()
        {
            GetThumbnailList();
            base.OnListDocumentUpdated();
        }

        #endregion

        #region Events XAML

        private void ListBoxVignette_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            SelectedDocumentIndex = ListBoxVignette.SelectedIndex;
            ManageToolbarState();
            OnItemsSelected(GetListDocumentFromSelectedThumbnails());
        }

        /// <summary>
        /// Handles the Loaded event of the UCViewerCore control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void UCViewerCore_Loaded(object sender, RoutedEventArgs e)
        {
            ListBoxVignette.Focus();
            FireOnInitialisationCompleted();
        }

        #endregion

        #region Load and refresh vignettes

        /// <summary>
        /// Load vignettes
        /// </summary>
        public void GetThumbnailList()
        {
            if (!m_bReloadThumbnail)
            {
                m_bReloadThumbnail = true;
                return;
            }

            List<string> l_oListDocument = new List<string>();
            List<string> l_oOriginalDocument = new List<string>();

            try
            {
                if ((ListDocument != null) && (ListDocument.Count > 0))
                {

                    TextBlockMode.Visibility = System.Windows.Visibility.Collapsed;
                    var documents = this.ListDocument;
                    foreach (Document l_oDoc in documents)
                    {
                        l_oOriginalDocument.Add(Path.Combine(Path.Combine(ParameterStorage, l_oDoc.RelativePath), l_oDoc.ImageName));
                        l_oListDocument.Add(AddThumbnailExtension(Path.Combine(ParameterStorageThumbnail, l_oDoc.RelativePath, l_oDoc.ImageName)));
                    }

                    SplashScreenManager.Wait(this);

                    WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                    L_oWCFServiceClient.GetImageFromFullPathCompleted += wcfServiceClientGetImageFromFullPathCompleted;
                    L_oWCFServiceClient.GetImageFromFullPathAsync(new ObservableCollection<string>(l_oListDocument), new ObservableCollection<string>(l_oOriginalDocument), ServiceManager.GetLicenseKey());
                }
                else
                {
                    OnItemsLoaded(null);
                    TextBlockMode.Visibility = System.Windows.Visibility.Visible;
                    ListBoxVignetteClear();
                    CursorNormal(this);
                }
            }
            catch (Exception ex)
            {
                CursorNormal(this);

                //Show error page
                ErrorPage errorPage = new ErrorPage(ex, "GetThumbnailList");
                errorPage.Show();
            }
        }

        /// <summary>
        /// CallBack of 'GetThumbnailList()'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void wcfServiceClientGetImageFromFullPathCompleted(object sender, GetImageFromFullPathCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                int selectedDocumentIndexSaved = SelectedDocumentIndex;

                List<ImageRio> l_oImageRioList = new List<ImageRio>(e.Result);
                ListItemSource = new ObservableCollection<ImageRioSearch>();

                int identifierCounter = 0;
                foreach (ImageRio ImgRio in l_oImageRioList)
                {
                    // Is very important to get the document identifier, to preserve the unique identifier!
                    // There is several rows with the same informations in r_doc, only the identifier change!! (ex: Paste and copy)
                    if (ListDocument.Count > identifierCounter)
                    {
                        long DocumentIdentifier = ListDocument[identifierCounter].Identifier;
                        Document l_szImageRioDoc = ListDocument.Where(item => Path.GetFileName(AddThumbnailExtension(item.ImageName)).Equals(ImgRio.Name)).FirstOrDefault();

                        if (l_szImageRioDoc != null)
                        {
                            ImageRioSearch imgRioSearch = new ImageRioSearch(DocumentIdentifier, ImgRio.Name, ImgRio.Img,
                                                                             ImgRio.ImageSize,
                                                                             l_szImageRioDoc.OriginalNameFile,
                                                                             l_szImageRioDoc.ImageName,
                                                                             l_szImageRioDoc.RelativePath,
                                                                             ImgRio.NumberPages)
                                                              {
                                                                  CreationDate = ImgRio.CreationDate,
                                                                  LastModificationDate = ImgRio.LastModificationDate,
                                                                  ImageSize = ImgRio.ImageSize,
                                                                  Dimension = ImgRio.Dimension,
                                                                  Resolution = ImgRio.Resolution,
                                                                  Author = ImgRio.Author,
                                                                  LastModificationAuthor = ImgRio.LastModificationAuthor,
                                                                  WorkflowState = (WorkflowState)
                                                                                  Enum.Parse(typeof (WorkflowState),
                                                                                             l_szImageRioDoc.
                                                                                                 WorkflowState.ToString(),
                                                                                             true),
                                                              };


                            if (m_oFolder != null && m_oFolder.FullTextDocList != null && m_oFolder.FullTextDocList.Any(f => f.Equals(Path.Combine(l_szImageRioDoc.RelativePath, l_szImageRioDoc.ImageName))))
                            {
                                imgRioSearch.IsFullSearch = true;
                            }

                            ListItemSource.Add(imgRioSearch);
                        }
                    }
                    identifierCounter++;
                }

                //Search the current selected item
                if (selectedDocumentIndexSaved >= 0 && ListItemSource.Count > selectedDocumentIndexSaved)
                {
                    ListBoxVignette.SelectedItem = ListItemSource.ElementAt(selectedDocumentIndexSaved);
                }

                // Set copied files theme
                foreach (var id in GlobalWebContext.CopyPasteManager.Documents)
                {
                    try
                    {
                        ListBoxVignette.ItemsSource.Cast<ImageRioSearch>().Where(t => t.Identifier == id).FirstOrDefault().IsCutedOrCopied = true;
                    }
                    catch { }
                }

                CursorNormal(this);
            }
        }

        /// <summary>
        /// Return a Document list from the selected thumbnails
        /// </summary>
        /// <returns></returns>
        public new List<Document> GetListDocumentFromSelectedThumbnails()
        {
            List<Document> L_oListDocument = new List<Document>();
            if ((ListBoxVignette.SelectedItems != null) && (ListBoxVignette.SelectedItems.Count > 0) && (ListDocument != null))
            {
                foreach (ImageRioSearch imgSearch in ListBoxVignette.SelectedItems)
                {
                    long imageIdentifier = imgSearch.Identifier;
                    foreach (Document doc in ListDocument)
                    {
                        if (imageIdentifier == doc.Identifier)
                        {
                            L_oListDocument.Add(doc);
                            break;
                        }
                    }
                }
            }

            return L_oListDocument;
        }

        /// <summary>
        /// Gets the list all documents.
        /// </summary>
        /// <returns></returns>
        public new List<Document> GetListAllDocuments()
        {
            List<Document> L_oListDocument = new List<Document>();
            if ((ListBoxVignette.SelectedItems != null) && (ListBoxVignette.SelectedItems.Count > 0) && (ListDocument != null))
            {
                foreach (ImageRioSearch imgSearch in ListBoxVignette.Items)
                {
                    long imageIdentifier = imgSearch.Identifier;
                    foreach (Document doc in ListDocument)
                    {
                        if (imageIdentifier == doc.Identifier)
                        {
                            L_oListDocument.Add(doc);
                            break;
                        }
                    }
                }
            }

            return L_oListDocument;
        }

        /// <summary>
        /// return a list of all document fullname 
        /// ( this function enable to keep the order given by the user with the drag and drop)
        /// </summary>
        /// <returns></returns>
        public List<string> GetListFullNameAllDocument()
        {
            List<string> L_oListAllDocument = new List<string>();
            if ((ListBoxVignette.Items != null) && (ListBoxVignette.Items.Count > 0) && (ListDocument != null))
            {
                foreach (ImageRioSearch imgSearch in ListBoxVignette.Items)
                {
                    //L_szImageSearchName = imgSearch.ImageName;
                    long imageIdentifier = imgSearch.Identifier;

                    foreach (Document doc in ListDocument)
                    {
                        if (imageIdentifier == doc.Identifier)
                        {
                            L_oListAllDocument.Add(Path.Combine(doc.RelativePath, doc.ImageName));
                            break;
                        }
                    }
                }
            }

            return L_oListAllDocument;
        }

        /// <summary>
        /// Indicate whether if the document can be rotated
        /// </summary>
        private void CanRotateAllFiles()
        {
            if ((ListBoxVignette.SelectedItems != null) && (ListBoxVignette.SelectedItems.Count > 0) && (ListDocument != null))
            {
                foreach (ImageRioSearch imgSearch in ListBoxVignette.SelectedItems)
                {
                    string L_szImageSearchName = imgSearch.ImageName;
                    if (Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.DOC.szGetDescription()
                    || Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.DOCX.szGetDescription()
                    || Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.PPT.szGetDescription()
                    || Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.PPTX.szGetDescription()
                    || Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.RTF.szGetDescription()
                    || Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.TXT.szGetDescription()
                    || Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.XLS.szGetDescription()
                    || Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.XLSX.szGetDescription()
                    )
                    {
                        MessageBoxChildWindow L_oMessageGetDocument = new MessageBoxChildWindow("", LabelRotateUnsupportedFile, MessageBoxButtons.Ok, MessageBoxIcon.Information);
                        L_oMessageGetDocument.Show();
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Return a ImageRioSearch list from the selected thumbnails
        /// </summary>
        /// <returns>List of <see cref="ImageRioSearch" /></returns>
        public override List<T> GetSelectedImage<T>()
        {
            List<T> resultList = new List<T>();
            if ((ListBoxVignette.SelectedItems != null) && (ListBoxVignette.SelectedItems.Count > 0) && (ListDocument != null))
            {
                foreach (T imgSearch in ListBoxVignette.SelectedItems)
                {
                    resultList.Add(imgSearch);
                }
            }
            return resultList;
        }

        /// <summary>
        /// Sets the selected image search.
        /// </summary>
        /// <param name="images">The images.</param>
        public override void SetSelectedImage<T>(List<T> images)
        {
            ListBoxVignette.SelectedItems.Clear();
            foreach (var imageRioSearch in images)
            {
                ListBoxVignette.SelectedItems.Add(imageRioSearch);
            }
        }

        #endregion

        #region Rotation

        /// <summary>
        /// Handles the Click event of the RotateLeftMenu control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Telerik.Windows.RadRoutedEventArgs" /> instance containing the event data.</param>
        private void OnRotateLeft()
        {
            ApplyRotateMenuClick(false);

            CanRotateAllFiles();
        }

        /// <summary>
        /// Handles the Click event of the RotateRightMenu control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Telerik.Windows.RadRoutedEventArgs" /> instance containing the event data.</param>
        private void OnRotateRight()
        {
            ApplyRotateMenuClick(true);

            CanRotateAllFiles();
        }

        /// <summary>
        /// Apply a rotation to whole items selected
        /// </summary>
        /// <param name="p_bRotateRight">apply a right rotation otherwise a left one</param>
        private void ApplyRotateMenuClick(bool p_bRotateRight)
        {
            if (ListBoxVignette.SelectedItems != null && ListBoxVignette.SelectedItems.Count > 0)
            {
                foreach (ImageRioSearch itemVignette in ListBoxVignette.SelectedItems)
                {
                    //string l_sRelativeDocumentPath = itemVignette.Name.Substring(0, itemVignette.Name.Length - Path.GetExtension(itemVignette.Name).Length);
                    string l_sRelativeDocumentPath = itemVignette.ImageName;
                    string l_szExtension = Path.GetExtension(l_sRelativeDocumentPath);
                    string l_sThumbnailFullPath = Path.Combine(ParameterStorageThumbnail, itemVignette.ThumbnailFullPath);

                    string l_ThumbnailFullPath = Path.Combine(ParameterStorageThumbnail, itemVignette.ThumbnailFullPath);
                    string l_sDocumentFullPath = Path.Combine(ParameterStorage, itemVignette.ImageFullPath);
                    if (l_szExtension.ToLower().Equals(".tif") || l_szExtension.ToLower().Equals(".tiff"))
                    {
                        // Call to know the number of pages from a document
                        //l_ThumbnailFullPath.Substring(0, l_ThumbnailFullPath.Length - Path.GetExtension(l_ThumbnailFullPath).Length);
                        WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                        L_oWCFServiceClient.GetPageCountFromTiffFullPathAsync(l_sDocumentFullPath, ServiceManager.GetLicenseKey(), Tuple.Create(itemVignette.ImageFullPath + "#" + l_sThumbnailFullPath, itemVignette, p_bRotateRight));
                        L_oWCFServiceClient.GetPageCountFromTiffFullPathCompleted += L_oWCFServiceClient_GetPageCountFromTiffFullPathCompleted;
                    }
                    else
                    {
                        //RotateDocumentWCFServices(DisplayRotatedThumbnail, ParameterStorageThumbnail, itemVignette.Name, itemVignette.Img, p_bRotateRight, ListBoxVignette.SelectedItems.IndexOf(itemVignette), 1, true);

                        if (l_szExtension.ToLower().Equals(".pdf"))
                        {
                            // Call to know the number of pages from a document
                            WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                            L_oWCFServiceClient.GetPageCountFromPdfFullPathAsync(l_sDocumentFullPath, ServiceManager.GetLicenseKey(), Tuple.Create(itemVignette.ImageFullPath + "#" + l_sThumbnailFullPath, itemVignette, p_bRotateRight));
                            L_oWCFServiceClient.GetPageCountFromPdfFullPathCompleted += new EventHandler<GetPageCountFromPdfFullPathCompletedEventArgs>(L_oWCFServiceClient_GetPageCountFromPdfFullPathCompleted);
                        }
                        else
                        {

                            RotateDocumentWCFServices(DisplayRotatedThumbnail, ParameterStorage, itemVignette.ImageFullPath + "#" + l_sThumbnailFullPath, itemVignette.Img, p_bRotateRight, ListBoxVignette.SelectedItems.IndexOf(itemVignette), 1, true);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// CallBack of 'GetPageCountFromPdfFullPath'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void L_oWCFServiceClient_GetPageCountFromPdfFullPathCompleted(object sender, GetPageCountFromPdfFullPathCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                //Logger.Write("EXCEPTION : " + Environment.NewLine + e.Error.Message, Logger.Level.Error);
                MessageBoxChildWindow L_oMessageGetDocument = new MessageBoxChildWindow("", "Error On GetPageCountFromTiffFullPath() -> " + e.Error.Message, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                L_oMessageGetDocument.Show();
            }
            else
            {
                ReturnLong l_oReturnLong = e.Result;
                if (l_oReturnLong.IsValid == false)
                {
                    //Logger.Write("NOT VALID : " + Environment.NewLine + l_oReturnLong.ErrorMessage, Logger.Level.Error);
                    MessageBoxChildWindow L_oMessageGetDocument = new MessageBoxChildWindow("", "Response not valid On GetPageCountFromTiffFullPath() -> " + l_oReturnLong.ErrorMessage, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                    L_oMessageGetDocument.Show();
                }
                else
                {
                    Tuple<string, ImageRioSearch, bool> l_oRet = (Tuple<string, ImageRioSearch, bool>)e.UserState;
                    //RotateDocumentWCFServices(DisplayRotatedThumbnail, ParameterStorageThumbnail, l_oRet.Item1, l_oRet.Item2.Img, l_oRet.Item3, ListBoxVignette.SelectedItems.IndexOf(l_oRet.Item2), 1, true, (int)e.Result.Value);
                    RotateDocumentWCFServices(DisplayRotatedThumbnail, ParameterStorage, l_oRet.Item1, l_oRet.Item2.Img, l_oRet.Item3, ListBoxVignette.SelectedItems.IndexOf(l_oRet.Item2), 1, true, (int)e.Result.Value);
                }
            }
        }

        /// <summary>
        /// CallBack of 'GetPageCountFromTiffFullPath'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void L_oWCFServiceClient_GetPageCountFromTiffFullPathCompleted(object sender, GetPageCountFromTiffFullPathCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                //Logger.Write("EXCEPTION : " + Environment.NewLine + e.Error.Message, Logger.Level.Error);
                MessageBoxChildWindow L_oMessageGetDocument = new MessageBoxChildWindow("", "Error On GetPageCountFromTiffFullPath() -> " + e.Error.Message, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                L_oMessageGetDocument.Show();
            }
            else
            {
                ReturnLong l_oReturnLong = e.Result;
                if (l_oReturnLong.IsValid == false)
                {
                    //Logger.Write("NOT VALID : " + Environment.NewLine + l_oReturnLong.ErrorMessage, Logger.Level.Error);
                    MessageBoxChildWindow L_oMessageGetDocument = new MessageBoxChildWindow("", "Response not valid On GetPageCountFromTiffFullPath() -> " + l_oReturnLong.ErrorMessage, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                    L_oMessageGetDocument.Show();
                }
                else
                {
                    Tuple<string, ImageRioSearch, bool> l_oRet = (Tuple<string, ImageRioSearch, bool>)e.UserState;
                    //RotateDocumentWCFServices(DisplayRotatedThumbnail, ParameterStorageThumbnail, l_oRet.Item1, l_oRet.Item2.Img, l_oRet.Item3, ListBoxVignette.SelectedItems.IndexOf(l_oRet.Item2), 1, true, (int)e.Result.Value);
                    RotateDocumentWCFServices(DisplayRotatedThumbnail, ParameterStorage, l_oRet.Item1, l_oRet.Item2.Img, l_oRet.Item3, ListBoxVignette.SelectedItems.IndexOf(l_oRet.Item2), 1, true, (int)e.Result.Value);
                }
            }
        }
        /// <summary>
        /// DisplayRotatedThumbnail
        /// </summary>
        /// <param name="p_aRawImage">Raw image</param>
        /// <param name="p_iIndexDocumentSelected">Index of selected document</param>
        /// <param name="p_iNbOfPage">Nb of document pages</param>
        private void DisplayRotatedThumbnail(Byte[] p_aRawImage, int p_iIndexDocumentSelected, int p_iNbOfPage)
        {
            ((ImageRioSearch)ListBoxVignette.SelectedItems[p_iIndexDocumentSelected]).Img = p_aRawImage;
        }
        #endregion

        #region Toolbar

        /// <summary>
        /// Handles the DocumentRibbonBarEvent event of the DocumentToolbar control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Rio.Framework.Pages.Events.DocumentRibbonBarEventArgs" /> instance containing the event data.</param>
        private void DocumentToolbar_DocumentRibbonBarEvent(object sender, Events.DocumentRibbonBarEventArgs args)
        {
            switch (args.DocumentRibbonBarMenuItem)
            {
                #region Selection
                case DocumentRibbonBarMenuItems.SelectAll:
                    OnSelectAll();
                    break;
                case DocumentRibbonBarMenuItems.SelectNone:
                    ClearSelectedThumbnails();
                    break;
                #endregion

                #region Display Mode
                case AppCode.Enums.DocumentRibbonBarMenuItems.DocumentMode:
                    DocumentContextMenu.ManageContextMenuItemState();
                    DocumentToolbar.ManageToolbar();
                    DocumentToolbar.HideMinimizedPopup();
                    OnActivateViewerMode();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.ThumbnailsMode:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.ListMode:
                    DocumentContextMenu.ManageContextMenuItemState();
                    DocumentToolbar.ManageToolbar();
                    DocumentToolbar.HideMinimizedPopup();
                    OnActivateListMode();
                    break;
                #endregion

                #region Fitting
                case AppCode.Enums.DocumentRibbonBarMenuItems.FitHeight:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.FitWidth:
                    break;

                #endregion

                #region Zoom
                case AppCode.Enums.DocumentRibbonBarMenuItems.ZoomIn:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.ZoomOut:
                    break;
                #endregion

                #region Rotate
                case AppCode.Enums.DocumentRibbonBarMenuItems.RotateLeft:
                    OnRotateLeft();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.RotateRight:
                    OnRotateRight();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.SaveModifications:
                    break;

                #endregion

                #region Search
                case AppCode.Enums.DocumentRibbonBarMenuItems.SearchNext:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.SearchPrevious:
                    break;
                #endregion

                #region Actions
                case AppCode.Enums.DocumentRibbonBarMenuItems.SendEmail:
                    OnSendMailClick();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Delete:
                    OnItemDeleteClick();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.MergePDF:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Download:
                    OnSaveDocumentClick();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Print:
                    PrintIndexedDocuments(ListBoxVignette.SelectedItems);
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.AddDocument:
                    OnAddDocumentEvent();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.SplitPDF:
                    break;
                case DocumentRibbonBarMenuItems.FolderLink:
                    ShowFolderLinkWindow();
                    break;
                #endregion

                #region Edit
                case AppCode.Enums.DocumentRibbonBarMenuItems.Cut:
                    OnCutClick();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Copy:
                    OnCopyClick();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Paste:
                    OnPasteClick();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.CheckOut:
                    OnCheckOutClick();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.CheckIn:
                    OnCheckInClick();
                    break;
                #endregion

                #region Workflow
                case AppCode.Enums.DocumentRibbonBarMenuItems.Ventilate:
                    OnVentilClick();
                    break;
                #endregion

                #region Outlook
                case AppCode.Enums.DocumentRibbonBarMenuItems.OpenDirectory:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.ReturnDirectory:
                    break;
                #endregion

            }
        }

        /// <summary>
        /// Handles the Click event of the SelectAll control.
        /// </summary>
        private void OnSelectAll()
        {
            foreach (ImageRioSearch ImgRioSearch in ListBoxVignette.Items)
            {
                ListBoxVignette.SelectedItems.Add(ImgRioSearch);
            }
            ListBoxVignette.Focus();
        }

        /// <summary>
        /// Clears the selected thumbnails.
        /// </summary>
        private void ClearSelectedThumbnails()
        {
            ListBoxVignette.SelectedItems.Clear();
        }

        /// <summary>
        /// Lists the box vignette clear.
        /// </summary>
        private void ListBoxVignetteClear()
        {
            ListBoxVignette.ItemsSource = null;
        }

        /// <summary>
        /// Manage state of toolbar icons following listbox thumbnails selection
        /// </summary>
        public override void ManageToolbarState()
        {
            if (ListBoxVignette.SelectedItems != null)
            {
                DocumentToolbar.SelectedDocumentCount = ListBoxVignette.SelectedItems.Count;
                DocumentContextMenu.SelectedDocumentCount = ListBoxVignette.SelectedItems.Count;

                if (ListBoxVignette.SelectedItems.Count > 0)
                {
                    DocumentToolbar.ChangeAppDisplayMode(AppDisplayMode.Search);
                    DocumentContextMenu.ChangeAppDisplayMode(AppDisplayMode.Search);
                }
                else
                {
                    DocumentToolbar.ChangeAppDisplayMode(AppDisplayMode.SearchNone);
                    DocumentContextMenu.ChangeAppDisplayMode(AppDisplayMode.SearchNone);

                    if (GlobalWebContext.CopyPasteManager.HasDocument)
                    {
                        DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.Paste, true);
                    }
                }
            }
            else
            {
                DocumentToolbar.SelectedDocumentCount = 0;
                DocumentContextMenu.SelectedDocumentCount = 0;

                DocumentToolbar.ChangeAppDisplayMode(AppDisplayMode.SearchNone);

                if (GlobalWebContext.CopyPasteManager.HasDocument)
                {
                    DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.Paste, true);
                }
            }

            DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.CheckOut, false);
            DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.CheckIn, false);

            OnToolbarStateHasChanged();
        }

        #endregion

        #region UpdateDocumentRank
        /// <summary>
        /// Save vignette position
        /// </summary>
        public void SavePosition()
        {
            if (m_bCanModify)
            {
                string L_szPositionDocuments = string.Empty;
                BusinessEntitiesDomainContext l_oBusinessEntitiesDomainContext = new BusinessEntitiesDomainContext();
                try
                {
                    if ((ListBoxVignette != null) && (ListBoxVignette.Items != null) && (ListBoxVignette.Items.Count > 0))
                    {
                        //Build a string with document identifier and it position
                        for (int i = 0; i < ListBoxVignette.Items.Count; i++)
                        {
                            L_szPositionDocuments = L_szPositionDocuments + ((ImageRioSearch)ListBoxVignette.Items[i]).Identifier + ";" + (i + 1) + ";#";
                        }

                        var query = l_oBusinessEntitiesDomainContext.UpdateDocumentRankQuery(L_szPositionDocuments);
                        l_oBusinessEntitiesDomainContext.Load(query, OnUpdateDocumentRankQueryCallback, null);
                        m_bReloadThumbnail = false;
                    }
                }
                catch
                {
                    SplashScreenManager.Stop(this);
                    MessageBoxChildWindow L_oMessageGetDocument = new MessageBoxChildWindow("", "Error On position saving.", MessageBoxButtons.Ok, MessageBoxIcon.Error);
                    L_oMessageGetDocument.Show();
                }
            }
        }

        /// <summary>
        /// Enable to load the viewer with the image selected
        /// </summary>
        /// <param name="result">The result.</param>
        public void OnUpdateDocumentRankQueryCallback(LoadOperation/*<ReturnBoolean>*/ result)
        {
            if (result.Error != null)
            {
                //Logger.Write("EXCEPTION : " + Environment.NewLine + result.Error.Message, Logger.Level.Error);
                MessageBoxChildWindow L_oMessageGetDocument = new MessageBoxChildWindow("", "Error On position saving callback.", MessageBoxButtons.Ok, MessageBoxIcon.Error);
                L_oMessageGetDocument.Show();
                L_oMessageGetDocument.Closed += (s, ev) => OnRefreshThumbnails();
            }
            else
            {
                Action onDocumentRankAction = delegate
                {
                    OnDocumentRank();
                };

                //Launch treatment
                Dispatcher.BeginInvoke(onDocumentRankAction);
            }
        }

        public event EventHandler DocumentRankEventHandler;
        private void OnDocumentRank()
        {
            if (DocumentRankEventHandler != null)
            {
                DocumentRankEventHandler(this, null);
            }
        }

        #endregion

        #region Send Mail

        /// <summary>
        /// Called when [send mail click].
        /// </summary>
        private void OnSendMailClick()
        {
            SendMail(GetListDocumentFromSelectedThumbnails());
        }
        #endregion

        #region Delete items

        /// <summary>
        /// Called when [item delete click].
        /// </summary>
        private void OnItemDeleteClick()
        {
            if (ListBoxVignette.SelectedItems != null)
                RemoveOrDeleteSelectedDocuments(ListBoxVignette.SelectedItems.Cast<ImageRioSearch>().Select(item => item.Identifier).ToList(), OnDeleteDocumentQueryCallback);
        }

        /// <summary>
        /// Called when [delete document query callback].
        /// </summary>
        /// <param name="result">The result.</param>
        private void OnDeleteDocumentQueryCallback(LoadOperation<NetBay.Core.BusinessEntities.ReturnObject> result)
        {
            if (result.Error != null)
            {
                //Logger.Write("EXCEPTION : " + Environment.NewLine + result.Error, Logger.Level.Error);
            }
            else
            {
                // Remove selectedFileName
                List<ImageRioSearch> L_oListImageDeleted = new List<ImageRioSearch>();

                if (ListBoxVignette.SelectedItems != null && ListBoxVignette.SelectedItems.Count > 0)
                {
                    L_oListImageDeleted.AddRange(ListBoxVignette.SelectedItems.Cast<ImageRioSearch>());
                }

                List<Document> L_oListDocumentDeleted = GetListDocumentFromSelectedThumbnails();

                foreach (ImageRioSearch item in L_oListImageDeleted)
                {
                    ObservableCollection<ImageRioSearch> src = (ObservableCollection<ImageRioSearch>)ListBoxVignette.ItemsSource;
                    src.Remove(item);
                }

                TextBlockMode.Visibility = ListBoxVignette.Items.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
                OnItemsDeletedToRemove(L_oListDocumentDeleted);

                //Stop SplashScreen after delete
                CursorNormal(this);
                SplashScreenManager.Stop(this);
            }
        }

        #endregion

        #region Ventil

        /// <summary>
        /// Called when [ventil click].
        /// </summary>
        private void OnVentilClick()
        {
            VentilateDocuments(ListBoxVignette.SelectedItems);
        }
        #endregion

        #region SaveDocument

        /// <summary>
        /// Called when [save document click].
        /// </summary>
        private void OnSaveDocumentClick()
        {
            //Log.
            Logger.Write("ListVignetteSearch.xaml.OnSaveDocumentClick (No parameters)...", Logger.Level.Debug);

            try
            {
                #region SaveFileDialog option
                //SaveFileDialog L_oSaveFileDialog = new SaveFileDialog();
                //string l_szExtension = Path.GetExtension(GetFileNameSelected);
                //L_oSaveFileDialog.DefaultExt = l_szExtension;
                //L_oSaveFileDialog.Filter = l_szExtension.Substring(1).ToUpper() + "| *" + l_szExtension;


                //bool? L_oDialogResult = L_oSaveFileDialog.ShowDialog();

                //if (L_oDialogResult == true)
                //{
                //    using (Stream fs = L_oSaveFileDialog.OpenFile())
                //    {
                //        fs.Write(m_aRawImage, 0, m_aRawImage.Length);
                //        fs.Close();
                //    }
                //}
                #endregion

                if (ListBoxVignette.SelectedItems.Count == 1)
                {
                    ImageRioSearch l_oSelectedThumbnail = (ImageRioSearch)ListBoxVignette.SelectedItem;
                    Document l_oSelectedDocument = ListDocument.Where(f => f.ImageName.Equals(l_oSelectedThumbnail.ImageName)).FirstOrDefault();
                    
                    if (l_oSelectedDocument != null)
                    {
                        BusinessEntitiesDomainContext l_oBecDC = new BusinessEntitiesDomainContext();
                        var query = l_oBecDC.AddActionHistoricQuery((int)Constant.UserActions.TELECHARGEMENT, 0, 0, null, l_oSelectedDocument.ImageName);
                        l_oBecDC.Load(query);

                        //Build URI
                        WebClient webClient = new WebClient();
                        Uri baseUri = new Uri(webClient.BaseAddress);
                        UriBuilder uriBuilder = new UriBuilder(baseUri.Scheme, baseUri.Host, baseUri.Port);

                        string path = uriBuilder.ToString().TrimEnd('/');
                        string filename = "/Rio.Application.FileDownload.aspx?fp=" + Path.Combine(ParameterStorage, l_oSelectedDocument.RelativePath, l_oSelectedDocument.ImageName) + "&name=" + l_oSelectedDocument.OriginalNameFile;

                        VariableDomainContext L_vdcAppVirtualPath = new VariableDomainContext();
                        L_vdcAppVirtualPath.GetAppDomainAppVirtualPath(delegate(InvokeOperation<string> str)
                        {
                            HtmlPage.Window.Navigate(str.Value == "/"
                                                     ? new Uri(path + filename, UriKind.Absolute)
                                                     : new Uri(path + str.Value + filename,
                                                     UriKind.Absolute));
                        }
                        , null);
                    }
                }
            }
            catch (Exception ex)
            {
                //Log Error.
                Logger.Write("Exception [" + ex.Message + "]",Logger.Level.Error);
            }
        }
        #endregion

        #region Drag and Drop

        protected override void OnDropInfo(object sender, DragDropEventArgs e)
        {
            base.OnDropInfo(sender, e);

            if (e.Options.Status == DragStatus.DropComplete)
            {
                SavePosition();
            }
        }

        #endregion

        #region Copy-Cut-Paste

        /// <summary>
        /// Return an identifier list from the selected thumbnails.
        /// </summary>
        /// <returns>Lsit of identifiers.</returns>
        protected override List<long> GetListIdentifierToCopy()
        {
            List<long> resultList = new List<long>();

            //Reset all 
            foreach (var id in GlobalWebContext.CopyPasteManager.Documents)
            {
                var item = ListBoxVignette.ItemsSource.Cast<ImageRioSearch>().Where(t => t.Identifier == id).FirstOrDefault();
                if (item != null)
                {
                    item.IsCutedOrCopied = false;
                }
            }

            if ((ListBoxVignette.SelectedItems != null) && (ListBoxVignette.SelectedItems.Count > 0) && (ListDocument != null))
            {
                foreach (ImageRioSearch imgSearch in ListBoxVignette.SelectedItems)
                {
                    resultList.Add(imgSearch.Identifier);
                    imgSearch.IsCutedOrCopied = true; //Set visual state
                }
            }
            return resultList;
        }

        /// <summary>
        /// Updates the copy paste selection.
        /// </summary>
        public override void UpdateCopyPasteSelection()
        {
            if ((ListBoxVignette.Items != null) && (ListBoxVignette.Items.Count > 0) && (ListDocument != null))
            {
                foreach (ImageRioSearch imgSearch in ListBoxVignette.Items)
                {
                    var item = GlobalWebContext.CopyPasteManager.Documents.SingleOrDefault(t => t == imgSearch.Identifier);
                    if (item == 0)
                    {
                        imgSearch.IsCutedOrCopied = false;
                    }
                    else
                    {
                        imgSearch.IsCutedOrCopied = true;
                    }
                }
            }
        }

        #endregion

        #region Key handles

        /// <summary>
        /// Desactives key down event.
        /// </summary>
        public void DeactivateKeyPress()
        {
            KeyDown -= ImageViewer_KeyDown;
        }

        /// <summary>
        /// Active key down event.
        /// </summary>
        public void ActivateKeyPress()
        {
            KeyDown += ImageViewer_KeyDown;
        }

        /// <summary>
        /// Key down handle
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Input.KeyEventArgs" /> instance containing the event data.</param>
        private void ImageViewer_KeyDown(object sender, KeyEventArgs e)
        {
            //SUPPR
            if (e.Key == Key.Delete && DocumentToolbar.CanDelete)
            {
                OnItemDeleteClick();
                return;
            }

            //Ctrl + X
            if (e.Key == Key.X && DocumentToolbar.CanDelete)
            {
                if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
                {
                    OnCutClick();
                    return;
                }
            }

            //Ctrl + C
            if (e.Key == Key.C && DocumentToolbar.CanDownload)
            {
                if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
                {
                    OnCopyClick();
                    return;
                }
            }

            //Ctrl + V
            if (e.Key == Key.V && DocumentToolbar.CanModify)
            {
                if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
                {
                    OnPasteClick();
                    return;
                }
            }
        }

        #endregion

        /// <summary>
        /// Changes the consultation mode
        /// </summary>
        /// <param name="organization">Organization</param>
        /// <param name="folderType">Folder type</param>
        /// <param name="modeToApply">Mode to apply</param>
        /// <param name="isVersioningActivated">if set to <c>true</c> [is versioning activated].</param>
        public override void ChangeConsultationMode(NetBay.Core.BusinessEntities.Organization organization, NetBay.Core.BusinessEntities.FolderType folderType, ConsultationModeType modeToApply, bool isVersioningActivated = false)
        {
            //Apply rights before change the mode
            DocumentToolbar.SetUserPriviledges(folderType, organization);
            DocumentContextMenu.SetUserPriviledges(folderType, organization);

            DocumentToolbar.ConsultationMode = modeToApply;
            DocumentContextMenu.ConsultationMode = modeToApply;
            this.ConsultationMode = modeToApply;

            DocumentToolbar.IsVersioningEnabled = isVersioningActivated;
            DocumentContextMenu.IsVersioningEnabled = isVersioningActivated;
        }

    }
}
